﻿using System;
using System.Text;

namespace ooWii
{
	public class WiiBuffer
	{
		#region WiiBuffer

		public static UInt16 GetUInt16( byte[] buffer, int offset )
		{
			return (UInt16)( ( ( (UInt16)buffer[ offset ] ) << 8 ) | ( ( (UInt16)buffer[ offset + 1 ] ) << 0 ) );
		}

		public static UInt32 GetUInt32( byte[] buffer, int offset )
		{
			return ( ( (UInt32)buffer[ offset ] ) << 24 ) | ( ( (UInt32)buffer[ offset + 1 ] ) << 16 ) | ( ( (UInt32)buffer[ offset + 2 ] ) << 8 ) | ( ( (UInt32)buffer[ offset + 3 ] ) << 0 );
		}

		public static long GetUInt34( byte[] buffer, int offset )
		{
			return ( ( (long)buffer[ offset ] ) << 26 ) | ( ( (long)buffer[ offset + 1 ] ) << 18 ) | ( ( (long)buffer[ offset + 2 ] ) << 10 ) | ( ( (long)buffer[ offset + 3 ] ) << 2 );
		}

		public static UInt64 GetUInt64( byte[] buffer, int offset )
		{
			return ( ( (UInt64)GetUInt32( buffer, offset ) ) << 32 ) | ( (UInt64)GetUInt32( buffer, offset + 4 ) );
		}

		public static string GetString( byte[] buffer, int offset, int size )
		{
			StringBuilder stringBuilder = new StringBuilder( size );
			for( int i = 0; i < size; i++ )
			{
				char c = (char)buffer[ i + offset ];
				if( c == 0 )
				{
					break;
				}

				stringBuilder.Append( c );
			}

			return stringBuilder.ToString();
		}

		public static byte[] GetBytes( byte[] buffer, int offset, int size )
		{
			byte[] bytes = new byte[ size ];
			Buffer.BlockCopy( buffer, offset, bytes, 0, bytes.Length );
			return bytes;
		}

		public static int Align( int offset, int blockSize )
		{
			blockSize--;
			return ( offset + blockSize ) & ~blockSize;
		}

		public static long Align( long offset, long blockSize )
		{
			blockSize--;
			return ( offset + blockSize ) & ~blockSize;
		}

		#endregion
	}
}
